<template>
  <div class="knowledge-form-wrap">
    <el-form
      ref="form"
      :model="thisForm"
      :rules="rules"
      :size="formConf.formSize || 'medium'"
      :label-position="formConf.labelPosition || 'right'"
      :label-width="formConf.labelWidth ? formConf.labelWidth + 'px' : '140' + 'px'"
    >
      <div v-for="(item, index) in groupLayouts" :key="index" class="fieldSet">
        <legend>{{ item.componentName }}</legend>
        <div class="fieldSetContent">
          <el-row :gutter="20">
            <el-col v-for="(col, idx) in item.children" :key="idx" :span="col.span">
              <el-form-item
                class="labelUnwrap"
                :label="col.label"
                :prop="col.basicCode"
                :rules="[
                  {
                    required: col.jsRequired == 1 ? true : false,
                    message: '不能为空',
                    trigger: 'blur'
                  }
                ]"
              >
                <span slot="label">
                  <el-tooltip :content="col.label">
                    <span>{{ col.label }}</span>
                  </el-tooltip>
                </span>
                <!--单选select-->
                <el-select
                  v-if="col.formTypeName == 'selectsingle'"
                  v-model="thisForm[col.basicCode]"
                  :placeholder="'请选择' + col.label"
                  :disabled="col.isReadOnly == 1 ? true : false"
                >
                  <el-option
                    v-for="item in col.dictList"
                    :key="item.dictValue"
                    :label="item.dictLabel"
                    :value="item.dictValue"
                  />
                </el-select>
                <!--多选select-->
                <el-select
                  v-else-if="col.formTypeName == 'selectmulti'"
                  v-model="thisForm[col.basicCode]"
                  multiple
                  :placeholder="'请选择' + col.label"
                  :disabled="col.isReadOnly == 1 ? true : false"
                >
                  <el-option
                    v-for="item in col.dictList"
                    :key="item.dictValue"
                    :label="item.dictLabel"
                    :value="item.dictValue"
                  />
                </el-select>
                <!--日期-->
                <el-date-picker
                  v-else-if="col.formTypeName == 'date'"
                  v-model="thisForm[col.basicCode]"
                  value-format="yyyy-MM-dd"
                  align="right"
                  type="date"
                  placeholder="选择日期"
                  :picker-options="pickerOptions"
                  :disabled="col.isReadOnly == 1 ? true : false"
                />
                <!--日期时间-->
                <el-date-picker
                  v-else-if="col.formTypeName === 'datetime'"
                  v-model="thisForm[col.basicCode]"
                  value-format="yyyy-MM-dd HH:mm:ss"
                  type="datetime"
                  placeholder="选择日期时间"
                  align="right"
                  :picker-options="pickerOptions"
                  :disabled="col.isReadOnly == 1 ? true : false"
                />
                <!--单选-->
                <el-radio-group
                  v-else-if="col.formTypeName === 'radio'"
                  v-model="thisForm[col.basicCode]"
                  :disabled="col.isReadOnly == 1 ? true : false"
                >
                  <el-radio v-for="item in col.dictList" :label="item.dictValue">{{ item.dictLabel }}</el-radio>
                </el-radio-group>
                <!--checkbox-->
                <el-checkbox-group
                  v-else-if="col.formTypeName == 'checkbox'"
                  v-model="
                    thisForm[col.basicCode] === null || thisForm[col.basicCode] === undefined
                      ? []
                      : thisForm[col.basicCode]
                  "
                  :disabled="col.isReadOnly == 1 ? true : false"
                >
                  <el-checkbox v-for="item in col.dictList" :label="item.dictValue">{{ item.dictLabel }}</el-checkbox>
                </el-checkbox-group>

                <el-input-number
                  v-else-if="col.formTypeName == 'spinner'"
                  v-model="thisForm[col.basicCode]"
                  :label="col.label"
                  :disabled="col.isReadOnly == 1 ? true : false"
                />

                <UploadTable
                  v-else-if="col.formTypeName == 'upload'"
                  :col="col"
                  :part-id="thisForm['_id']"
                  :ref-type="col.uploadTypeId"
                  :field-id="col.fieldId"
                  @change="fileListChange"
                  :disabled="col.isReadOnly == 1 ? true : false"
                />
                <UploadFolder
                  v-else-if="pjOpen && col.formTypeName == 'upload_folder'"
                  :col="col"
                  :task-id="taskId"
                  :part-id="thisForm['_id']"
                  :ref-type="col.uploadTypeId"
                  :field-id="col.fieldId"
                  @change="uploadFolderChange"
                  :disabled="col.isReadOnly == 1 ? true : false"
                />

                <DataExtendTable
                  v-else-if="col.dataExtend == true"
                  :col="col"
                  :part-id="thisForm['_id']"
                  @change="dataExtendChange"
                />

                <!-- 颜色 -->
                <el-color-picker
                  v-else-if="col.formTypeName == 'color'"
                  v-model="thisForm[col.basicCode]"
                  show-alpha
                  :predefine="predefineColors"
                  :disabled="col.isReadOnly == 1 ? true : false"
                />

                <!--富文本(readOnly自带属性)-->
                <editor
                  v-else-if="col.formTypeName == 'richtext'"
                  v-model="thisForm[col.basicCode]"
                  :min-height="192"
                  :read-only="col.isReadOnly == 1 ? true : false"
                />

                <el-input
                  v-else-if="col.formTypeName === 'textarea'"
                  v-model="thisForm[col.basicCode]"
                  type="textarea"
                  :disabled="col.isReadOnly == 1 ? true : false"
                />
                <el-input
                  v-else-if="col.formTypeName == 'input'"
                  v-model="thisForm[col.basicCode]"
                  :placeholder="'请输入' + col.label"
                  :disabled="col.isReadOnly == 1 ? true : false"
                />

                <el-tree
                  :class="{ 'single-tree': col.isReadOnly != 1 }"
                  v-else-if="col.formTypeName === 'selectztree'"
                  :ref="col.basicCode"
                  :check-on-click-node="true"
                  :data="col.dictList"
                  show-checkbox
                  :default-checked-keys="[thisForm[col.basicCode]]"
                  node-key="dictValue"
                  :props="{
                    children: 'children',
                    label: 'dictLabel',
                    id: 'dictValue',
                    disabled: (data, node) => {
                      if (col.isReadOnly == 1) return true
                      return data.children && data.children.length > 0
                    }
                  }"
                  @check-change="(data, checked, node) => singleTreeClick(data, checked, node, col)"
                >
                </el-tree>

                <el-tree
                  v-else-if="col.formTypeName === 'selectztreemulti'"
                  :ref="col.basicCode"
                  :check-on-click-node="true"
                  :data="col.dictList"
                  show-checkbox
                  :default-checked-keys="thisForm[col.basicCode]"
                  node-key="dictValue"
                  :props="{
                    children: 'children',
                    label: 'dictLabel',
                    id: 'dictValue',
                    disabled: (data, node) => {
                      return data.children && data.children.length > 0
                    }
                  }"
                  @check-change="e => multiTreeClick(e, col)"
                  :disabled="col.isReadOnly == 1 ? true : false"
                >
                </el-tree>

                <div v-else v-show="col.isReadOnly == 1 ? true : false">{{ col.formTypeName }}</div>
                <!---->
              </el-form-item>
            </el-col>
          </el-row>
        </div>
      </div>
      <div v-if="groupOutLayouts != null && groupOutLayouts.length > 0" class="fieldSet">
        <legend>其他信息</legend>
        <div class="fieldSetContent">
          <el-row :gutter="20">
            <el-col v-for="(col, idx) in groupOutLayouts" :span="col.span">
              <!--<span>{{col.formTypeName}}</span>-->
              <el-form-item
                class="labelUnwrap"
                :label="col.label"
                :prop="col.basicCode"
                :rules="[
                  {
                    required: col.jsRequired == 1 ? true : false,
                    message: '不能为空',
                    trigger: 'blur'
                  }
                ]"
              >
                <span slot="label">
                  <el-tooltip :content="col.label">
                    <span>{{ col.label }}</span>
                  </el-tooltip>
                </span>
                <!--单选select-->
                <el-select
                  v-if="col.formTypeName == 'selectsingle'"
                  v-model="thisForm[col.basicCode]"
                  :placeholder="'请选择' + col.label"
                  :disabled="col.isReadOnly == 1 ? true : false"
                >
                  <el-option
                    v-for="item in col.dictList"
                    :key="item.dictValue"
                    :label="item.dictLabel"
                    :value="item.dictValue"
                  />
                </el-select>
                <!--多选select-->
                <el-select
                  v-else-if="col.formTypeName == 'selectmulti'"
                  v-model="thisForm[col.basicCode]"
                  multiple
                  :placeholder="'请选择' + col.label"
                  :disabled="col.isReadOnly == 1 ? true : false"
                >
                  <el-option
                    v-for="item in col.dictList"
                    :key="item.dictValue"
                    :label="item.dictLabel"
                    :value="item.dictValue"
                  />
                </el-select>
                <!--日期-->
                <el-date-picker
                  v-else-if="col.formTypeName == 'date'"
                  v-model="thisForm[col.basicCode]"
                  value-format="yyyy-MM-dd"
                  align="right"
                  type="date"
                  placeholder="选择日期"
                  :picker-options="pickerOptions"
                  :disabled="col.isReadOnly == 1 ? true : false"
                />
                <!--日期时间-->
                <el-date-picker
                  v-else-if="col.formTypeName === 'datetime'"
                  v-model="thisForm[col.basicCode]"
                  value-format="yyyy-MM-dd HH:mm:ss"
                  type="datetime"
                  placeholder="选择日期时间"
                  align="right"
                  :picker-options="pickerOptions"
                  :disabled="col.isReadOnly == 1 ? true : false"
                />
                <!--单选-->
                <el-radio-group
                  v-else-if="col.formTypeName === 'radio'"
                  v-model="thisForm[col.basicCode]"
                  :disabled="col.isReadOnly == 1 ? true : false"
                >
                  <el-radio v-for="item in col.dictList" :label="item.dictValue">{{ item.dictLabel }}</el-radio>
                </el-radio-group>
                <!--checkbox-->
                <!--解决未定义时异常-->
                <el-checkbox-group
                  v-else-if="col.formTypeName == 'checkbox'"
                  v-model="thisForm[col.basicCode] === null || thisForm[col.basicCode] === undefined? []: thisForm[col.basicCode]"
                  :disabled="col.isReadOnly == 1 ? true : false"
                >
                  <el-checkbox v-for="item in col.dictList" :label="item.dictValue">{{ item.dictLabel }}</el-checkbox>
                </el-checkbox-group>

                <el-input-number
                  v-else-if="col.formTypeName == 'spinner'"
                  v-model="thisForm[col.basicCode]"
                  :label="col.label"
                  :disabled="col.isReadOnly == 1 ? true : false"
                />

                <UploadTable
                  v-else-if="col.formTypeName == 'upload'"
                  :col="col"
                  :part-id="thisForm['_id']"
                  :ref-type="col.uploadTypeId"
                  :field-id="col.fieldId"
                  @change="fileListChange"
                />

                <UploadFolder
                  v-else-if="pjOpen && col.formTypeName == 'upload_folder'"
                  :col="col"
                  :task-id="taskId"
                  :part-id="thisForm['_id']"
                  :ref-type="col.uploadTypeId"
                  :field-id="col.fieldId"
                  @change="uploadFolderChange"
                />

                <DataExtendTable
                  v-else-if="col.dataExtend == true"
                  :col="col"
                  :part-id="thisForm['_id']"
                  @change="dataExtendChange"
                />

                <!-- 颜色 -->
                <el-color-picker
                  v-else-if="col.formTypeName == 'color'"
                  v-model="thisForm[col.basicCode]"
                  show-alpha
                  :predefine="predefineColors"
                  :disabled="col.isReadOnly == 1 ? true : false"
                />

                <!--富文本(readOnly自带属性)-->
                <editor
                  v-else-if="col.formTypeName == 'richtext'"
                  v-model="thisForm[col.basicCode]"
                  :min-height="192"
                  :read-only="col.isReadOnly == 1 ? true : false"
                />

                <el-input
                  v-else-if="col.formTypeName === 'textarea'"
                  v-model="thisForm[col.basicCode]"
                  type="textarea"
                  :disabled="col.isReadOnly == 1 ? true : false"
                />
                <el-input
                  v-else-if="col.formTypeName == 'input'"
                  v-model="thisForm[col.basicCode]"
                  :placeholder="'请输入' + col.label"
                  :disabled="col.isReadOnly == 1 ? true : false"
                />

                <el-tree
                  :class="{ 'single-tree': col.isReadOnly != 1 }"
                  v-else-if="col.formTypeName === 'selectztree'"
                  :ref="col.basicCode"
                  :check-on-click-node="true"
                  :data="col.dictList"
                  show-checkbox
                  :default-checked-keys="[thisForm[col.basicCode]]"
                  node-key="dictValue"
                  :props="{
                    children: 'children',
                    label: 'dictLabel',
                    id: 'dictValue',
                    disabled: (data, node) => {
                      if (col.isReadOnly == 1) return true
                      return data.children && data.children.length > 0
                    }
                  }"
                  @check-change="(data, checked, node) => singleTreeClick(data, checked, node, col)"
                >
                </el-tree>

                <el-tree
                  v-else-if="col.formTypeName === 'selectztreemulti'"
                  :ref="col.basicCode"
                  :check-on-click-node="true"
                  :data="col.dictList"
                  show-checkbox
                  :default-checked-keys="thisForm[col.basicCode]"
                  node-key="dictValue"
                  :props="{
                    children: 'children',
                    label: 'dictLabel',
                    id: 'dictValue',
                    disabled: (data, node) => {
                      return data.children && data.children.length > 0
                    }
                  }"
                  @check-change="e => multiTreeClick(e, col)"
                >
                </el-tree>
                <div v-else v-show="col.isReadOnly == 1 ? true : false">{{ col.formTypeName }}</div>
              </el-form-item>
            </el-col>
          </el-row>
        </div>
      </div>
    </el-form>
    <div
      slot="footer"
      class="dialog-footer"
    >
      <el-button type="primary" @click="submitForm('form')">确定</el-button>
      <el-button @click="changeFlag">取消</el-button>
    </div>

  </div>
</template>
<script>
import UploadTable from './UploadTable'
import DataExtendTable from './DataExtendTable'
import UploadFolder from './UploadFolder'

export default {
  name: 'DataEdit',
  components: {
    UploadTable,
    DataExtendTable,
    UploadFolder
  },
  props: {
    form: {
      type: Object,
      required: true,
      default: () => {}
    },
    groupLayouts: {
      type: Array,
      default: () => []
    },
    groupOutLayouts: {
      type: Array,
      default: null
    },
    pjOpen: {
      type: Boolean,
      default: false
    },
    formConf: {
      type: Object,
      default: null
    },
    taskId: {
      type: String,
      default: ''
    },
    operationType: {
      type: String,
      default: 'add'
    },
    modelId: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      ifShowByFieldId: {}, // 存放tag中input的显示和隐藏标识--以免多个ta标签出现连带(根据fieldId区分)
      nowTag_basicCode: '',
      nowTag_fieldId: '',
      nowMaxNum: -1, // 不做限制
      // -------end
      // 表单校验
      rules: {},
      pickerOptions: {
        shortcuts: [
          {
            text: '今天',
            onClick(picker) {
              picker.$emit('pick', new Date())
            }
          },
          {
            text: '昨天',
            onClick(picker) {
              const date = new Date()
              date.setTime(date.getTime() - 3600 * 1000 * 24)
              picker.$emit('pick', date)
            }
          },
          {
            text: '一周前',
            onClick(picker) {
              const date = new Date()
              date.setTime(date.getTime() - 3600 * 1000 * 24 * 7)
              picker.$emit('pick', date)
            }
          }
        ]
      },
      thisForm: {},
      predefineColors: [
        '#ff4500',
        '#ff8c00',
        '#ffd700',
        '#90ee90',
        '#00ced1',
        '#1e90ff',
        '#c71585',
        'rgba(255, 69, 0, 0.68)',
        'rgb(255, 120, 0)',
        'hsv(51, 100, 98)',
        'hsva(120, 40, 94, 0.5)',
        'hsl(181, 100%, 37%)',
        'hsla(209, 100%, 56%, 0.73)',
        '#c7158577'
      ]
    }
  },
  computed: {
    haveUploadFolder() {
      let find = null
      if (this.groupOutLayouts && this.groupOutLayouts.length) {
        find = this.groupOutLayouts.find(item => item.formTypeName === 'upload_folder')
      }
      if (find) {
        return true
      }
      if (this.groupLayouts && this.groupLayouts.length) {
        this.groupLayouts.forEach(layoutsItem =>
          layoutsItem.children.forEach(item => {
            if (item.formTypeName === 'upload_folder') {
              find = true
            }
          })
        )
      }
      if (find) {
        return true
      } else {
        return false
      }
    }
  },
  watch: {
    form: {
      handler(n) {
        this.formInit(n)
      }
    }
  },
  created() {
    this.formInit(this.form)
  },
  methods: {
    singleTreeClick(data, checked, node, col) {
      // 单选树
      console.log('singleTreeClick', data, checked, node, col)
      try {
        if (checked) {
          this.$refs[col.basicCode][0].setCheckedNodes([data])
        }
        let checkedNodes = this.$refs[col.basicCode][0].getCheckedNodes().map(item => {
          return item.dictValue
        })
        if (checkedNodes) {
          this.thisForm[col.basicCode] = checkedNodes[0]
        }
      } catch (error) {
        console.log('单选树', error)
      }
    },
    multiTreeClick(data, col) {
      // 多选树
      try {
        console.log('multiTreeClick', data, col)
        console.log(this.$refs[col.basicCode][0].getCheckedNodes())
        let checkedNodes = this.$refs[col.basicCode][0].getCheckedNodes().map(item => {
          return item.dictValue
        })
        if (checkedNodes) {
          this.thisForm[col.basicCode] = checkedNodes
        }
      } catch (error) {
        console.log('多选树', error)
      }
    },
    formInit(formObj) {
      // 编辑
      this.thisForm = JSON.parse(JSON.stringify(this.form))
    },
    /** 文件列表值变更 */
    fileListChange(a) {
      const l = []
      a.list.forEach(c => {
        l.push({
          fileId: c.id,
          fieldId: a.fieldId
        })
      })
      this.thisForm['_selfUploadFiles'] = l
    },
    uploadFolderChange(e) {
      // TODO 字段为必填时提交会校验，导致无法先新增条目
      console.log('uploadFolderChange', e)
    },
    /** * 复杂属性表格变更 */
    dataExtendChange(a) {
      console.log(a)
    },
    submitForm(formName, type) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          this.$emit('submit', this.thisForm)
        } else {
          console.log('error submit!!')
          this.$message.error('缺少必填信息，请完善后提交')
          return false
        }
      })
    },
    changeFlag() {
      this.$emit('update:pjOpen', false)
    },
    tagClose(tag, list) {
      list.splice(list.indexOf(tag), 1)
    },
    showInput(fieldId) {
      this.$set(this.ifShowByFieldId, fieldId, true)
    }
  }
}
</script>
<style lang="scss" scoped>
::v-deep .type-list-tab {
  margin-bottom: 10px;

  &.el-tabs--card .el-tabs__header .el-tabs__item.is-active {
    background-color: #409eff;
    color: #ffffff;
  }

  .el-tabs__nav-next,
  .el-tabs__nav-prev {
    height: 26px;
    line-height: 26px;
  }

  .el-tabs__item {
    cursor: pointer;
    padding: 0 14px;
    height: 26px;
    -webkit-box-sizing: border-box;
    box-sizing: border-box;
    line-height: 26px;
    display: inline-block;
    list-style: none;
    font-size: 12px;
    color: #303133;
    position: relative;
  }
}

.knowledge-form-wrap {
  .tab-box {
    margin-bottom: 10px;
  }
  .fieldSet {
    margin-bottom: 21px;
    padding: 5px;
    border: 1px #ededed solid;
    border-radius: 4px;
    display: block;
    box-shadow: rgba(99, 99, 99, 0.2) 2px 2px 5px 0px;
  }

  legend {
    display: block;
    position: relative;
    margin-top: -15px;
    background-color: white;
    width: fit-content;
    margin-left: 20px;
    margin-bottom: 5px;
    padding: 0 5px;
    font-size: 14px;
    font-weight: 700;
    line-height: inherit;
    color: #077ce9;
    border: 0;
  }

  .fieldSetContent {
    /*display: flex;*/
    margin-top: 2%;
  }

  .pjFormDialog .el-dialog__body {
    // padding: 12px 20px !important;
    // height: 84vh;
    // overflow-y: auto;
    // scroll-behavior: smooth;
  }

  .fieldSetContent .el-input {
    width: 100%;
  }

  .dialog-footer {
    text-align: right;
  }

  .el-tag + .el-tag {
    margin-left: 10px;
  }

  .button-new-tag {
    margin-left: 10px;
    height: 32px;
    line-height: 30px;
    padding-top: 0;
    padding-bottom: 0;
  }

  .input-new-tag {
    width: 90px;
    margin-left: 10px;
    vertical-align: bottom;
  }

  .input-new-tag {
    width: 90px !important;
  }

  .labelUnwrap label {
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }

  // 单选树隐藏父节点 ckeckbox
  ::v-deep .single-tree {
    .el-tree-node__content {
      .is-disabled {
        display: none;
      }
    }
  }

  .btn-box {
    // height: 40px;
    display: flex;
    justify-content: flex-end;
    padding-bottom: 10px;
    .btn {
      margin-left: 10px;
    }
  }
}
</style>
